import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/datas/provider_index_setting.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/mine/service/provider_unread_msg.dart';
import 'package:flutter_syt/generated/assets.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/image_picker_helper.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/auto_image.dart';
import 'package:provider/provider.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import 'simple_image_loader.dart';

class StupidTitleBarEntity {
  late String weatherIconUrl;
  late String temperature;
  late String position;

  StupidTitleBarEntity();

  factory StupidTitleBarEntity.create(
    String weatherIconUrl,
    String temperature,
    String position,
  ) {
    return StupidTitleBarEntity()
      ..weatherIconUrl = weatherIconUrl
      ..temperature = temperature
      ..position = position;
  }

  static StupidTitleBarEntity fake() {
    return StupidTitleBarEntity.create("weatherIconUrl", "32", "成都");
  }
}

enum BarType { SEARCH, SETTING }

class NormalTitleBar extends StatefulWidget {
  final StupidTitleBarEntity? weatherInfo;
  final BarType type;
  final bool isCompetitions;

  NormalTitleBar(this.weatherInfo,
      {this.type = BarType.SEARCH, this.isCompetitions = false});

  @override
  State<StatefulWidget> createState() => _NormalTitleBarState();
}

class _NormalTitleBarState extends State<NormalTitleBar> {
  // List<String> qrWhiteList = [];
  @override
  Widget build(BuildContext context) {
    Widget _logo() {
      return Container(
        width: 40,
        height: 40,
        child: Image.asset(
          "assets/icons/icon_login_colors.png",
          // icon_login_colors logo_white
          width: 40,
          height: 40,
        ),
      );
    }

    Widget _weather() {
      return Row(
        children: [
          Container(
            margin: EdgeInsets.only(left: 12),
            child: ImageLoader.loadImage(
              imageUrl: widget.weatherInfo!.weatherIconUrl,
              width: 15,
              height: 15,
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 6),
            child: Text(
              '${widget.weatherInfo!.temperature}°C',
              style: TextStyle(
                fontSize: 18,
                color: Colors.white,
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 6),
            child: Text(
              widget.weatherInfo!.position,
              style: TextStyle(
                fontSize: 12,
                color: Colors.white,
              ),
            ),
          )
        ],
      );
    }

    Widget _search(type) {
      return Container(
        margin: EdgeInsets.only(left: 12),
        width: 44,
        height: 35,
        child: Center(
          child: type == BarType.SEARCH
              ? Image.asset(
                  'assets/icons/icon_search_black.png',
                  width: 20,
                  height: 20,
                  color: Colors.white,
                )
              : Image.asset(
                  'assets/icons/icon_setting.png',
                  width: 20,
                  height: 20,
                  color: Colors.white,
                ),
        ),
      );
    }

    // Widget _message() {
    //   return Consumer<OnlineGlobalData>(builder: (key, ctx, child) {
    //     bool hasNew = OnlineGlobalData.shared.hasNewMessage;
    //     var content = Stack(
    //       children: [
    //         Container(
    //           // margin: EdgeInsets.only(
    //           //   left: 21,
    //           // ),
    //           width: 22,
    //           height: 35,
    //           child: Image.asset(
    //             'assets/icons/icon_message_black.png',
    //             width: 21,
    //             height: 18,
    //             color: Colors.white,
    //           ),
    //         ),
    //         if (hasNew)
    //           Positioned(
    //             top: 5,
    //             right: 10,
    //             child: Container(
    //               width: 10,
    //               height: 10,
    //               decoration: BoxDecoration(
    //                 color: Colors.red,
    //                 borderRadius: BorderRadius.all(
    //                   Radius.circular(10),
    //                 ),
    //               ),
    //             ),
    //           ),
    //       ],
    //     );
    //     return content;
    //   });
    // }

    return Row(
      children: [
        _logo(),
        if (widget.weatherInfo != null) _weather(),
        Spacer(),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: ClickUtils.debounce(() {
            if (widget.type == BarType.SEARCH) {
              RouteManager.push(
                  context, RoutMapping.search(widget.isCompetitions));
            } else {
              RouteManager.push(context, RoutMapping.settingPage());
            }
          }),
          child: _search(widget.type),
        ),
        Consumer<ProviderIndexSetting>(builder: (context, value, child) {
          return Visibility(
              visible: value.indexSetting.scan == 1,
              child: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: ClickUtils.debounce(() async {
                  // RouteManager.push(context, RoutMapping.message());
                  //TODO:扫码
                  UtilsOther.scanVenue(context);
                  // RouteManager.push(context, RoutMapping.message());
                }),
                child: Container(
                  width: 44,
                  height: 35,
                  child: Center(
                    child: Image.asset(
                      'assets/images/icon_titile_qr.png',
                      width: 20,
                      height: 20,
                      color: Colors.white,
                    ),
                  ),
                ),
              ));
        }),
        SizedBox(
          width: 15.w,
        ),
      ],
    );
  }
}

class ColorsTitleBar extends StatefulWidget {
  final StupidTitleBarEntity? weatherInfo;
  final BarType type;
  final bool isShowWeather;
  final String? title;
  final bool isShowQr;
  final bool isShowService;
  final bool isCompetitions;

  ColorsTitleBar(this.weatherInfo,
      {this.type = BarType.SEARCH,
      this.isShowWeather = true,
      this.title,
      this.isShowQr = false,
      this.isCompetitions = false,
      this.isShowService = false});

  @override
  State<StatefulWidget> createState() => _ColorsTitleBarState();
}

class _ColorsTitleBarState extends State<ColorsTitleBar> {
  List<String> qrWhiteList = [];
  List _sysTemBatch = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getSysTemBatch();
  }

  Future getSysTemBatch() async {
    var list = await API.shared.common.getSysTemBatch();
    // qrWhiteList = list;
    if (list is List) {
      _sysTemBatch = list;
    }
// {code: 200, message: OK, data: [{key: customer_hotline, value: 028-67563733}, {key: reserve_hotline, value: 021-33192277}, {key: hotline_copywriting, value: {"zh":"客服热线","en":"Hotline"}}, {key: email_copywriting, value: {"zh":"邮箱反馈","en":"E-mail"}}, {key: email_feedback, value: officialappservice@2021chengdu.com}, {key: reserve_copywriting, value: {"zh":"备用客服热线","en":"Alternate Hotline"}}, {key: online_copywriting, value: {"zh":"在线客服","en":"Online"}}]}
  }

  @override
  Widget build(BuildContext context) {
    Widget _logo() {
      return Container(
        width: 40,
        height: 40,
        child: Image.asset(
          "assets/icons/icon_login_colors.png",
          width: 40,
          height: 40,
        ),
      );
    }

    Widget _weather() {
      return Row(
        children: [
          Container(
            width: 32,
            height: 32,
            alignment: Alignment.center,
            margin: EdgeInsets.only(left: 12),
            child: ImageLoader.loadImage(
              imageUrl: widget.weatherInfo!.weatherIconUrl,
            ),
          ),
          Container(
              margin: EdgeInsets.only(left: 8),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '${widget.weatherInfo!.temperature}°C',
                    style: TextStyle(
                      fontSize: 16,
                      color: Color(0xff111111),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    widget.weatherInfo!.position,
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.bold,
                      color: Color(0xff111111),
                    ),
                  ),
                ],
              )),
          // Container(
          //   margin: EdgeInsets.only(left: 6),
          //   child: Text(
          //     widget.weatherInfo!.position,
          //     style: TextStyle(
          //       fontSize: 12,
          //       color: Colors.black,
          //     ),
          //   ),
          // )
        ],
      );
    }

    Widget _search(type) {
      return Container(
        margin: EdgeInsets.only(left: 10.w),

        // width: 35,
        // height: 35,
        // color: Colors.red,
        // child: Center(
        //   child: type == BarType.SEARCH
        //       ? Image.asset(
        //           'assets/icons/icon_search_black.png',
        //           width: 20,
        //           height: 20,
        //         )
        //       : Image.asset(
        //           'assets/icons/icon_setting.png',
        //           width: 24,
        //           height: 24,
        //         ),
        // ),
        child: SizedBox(
          width: 40,
          height: 40,
          child: Center(
            child: AutoImage(
              type == BarType.SEARCH
                  ? Assets.iconSearchBlack
                  : Assets.iconSetting,
              width: 20.w,
            ),
          ),
        ),
      );
    }

    Widget _service() {
      return Consumer<ProviderUnReadMsg>(
        builder: (context, value, child) {
          return Container(
              width: 35,
              height: 35,
              child: Stack(
                children: [
                  Positioned.fill(
                    child: Center(
                      child: Image.asset(
                        'assets/icons/icon_service.png',
                        width: 24,
                        height: 24,
                      ),
                    ),
                  ),
                  Positioned(
                      top: 4,
                      right: 4,
                      child: Visibility(
                          visible: value.unReadNum > 0,
                          child: Container(
                              width: 8,
                              height: 8,
                              decoration: BoxDecoration(
                                  color: Color(0xffEA2121),
                                  borderRadius: BorderRadius.circular(4)))))
                ],
              ));
        },
      );
    }

    // Widget _message() {
    //   return Consumer<OnlineGlobalData>(builder: (key, ctx, child) {
    //     bool hasNew = OnlineGlobalData.shared.hasNewMessage;
    //     var content = Stack(
    //       children: [
    //         Container(
    //           margin: EdgeInsets.only(left: 21, right: 14),
    //           width: 22,
    //           height: 35,
    //           child: Image.asset(
    //             'assets/icons/icon_message_black.png',
    //             width: 21,
    //             height: 18,
    //           ),
    //         ),
    //         if (hasNew)
    //           Positioned(
    //             top: 5,
    //             right: 10,
    //             child: Container(
    //               width: 10,
    //               height: 10,
    //               decoration: BoxDecoration(
    //                 color: Colors.red,
    //                 borderRadius: BorderRadius.all(
    //                   Radius.circular(10),
    //                 ),
    //               ),
    //             ),
    //           ),
    //       ],
    //     );
    //     return content;
    //   });
    // }

    return Container(
      height: 44,
      width: 1.sw,
      // color: Colors.red,
      child: Stack(
        children: [
          Visibility(
              visible: widget.title != null,
              child: Positioned.fill(
                  child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    widget.title ?? '',
                    style: FontStyles.headerTextStyle_18.copyWith(
                      fontWeight: FontWeight.w500,
                    ),
                  )
                ],
              ))),
          Positioned.fill(
              child: Row(
            children: [
              SizedBox(
                width: 20.w,
              ),
              _logo(),
              if (widget.weatherInfo != null && widget.isShowWeather)
                _weather(),
              Spacer(),
              Visibility(
                  visible: widget.isShowService,
                  child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () async {
                        if (UserInfo.me.isLogin) {
                          if (_sysTemBatch.isEmpty) {
                            await getSysTemBatch();
                          }
                          ProviderIndexSetting provider =
                              Provider.of<ProviderIndexSetting>(context,
                                  listen: false);

                          ProviderUnReadMsg unReadMsg =
                              Provider.of<ProviderUnReadMsg>(context,
                                  listen: false);
                          DialogHelper.showServiceBottom(
                              context, _sysTemBatch, provider, unReadMsg);
                          // RouteManager.push(
                          //     context, RoutMapping.service_socket('self'));
                        } else {
                          // DialogHelper.showServiceBottom(context);
                          RouteManager.push(
                            context,
                            RoutMapping.loginByPwd(),
                          );
                        }
                      },
                      child: _service())),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: ClickUtils.debounce(() {
                  if (widget.type == BarType.SEARCH) {
                    RouteManager.push(
                        context, RoutMapping.search(widget.isCompetitions));
                  } else {
                    RouteManager.push(context, RoutMapping.settingPage());
                  }
                }),
                child: _search(widget.type),
              ),

              Visibility(
                  visible: widget.isShowQr,
                  child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: ClickUtils.debounce(() async {
                      // RouteManager.push(context, RoutMapping.message());
                      //TODO:扫码
                      UtilsOther.scanVenue(context);
                      // RouteManager.push(context, RoutMapping.message());
                    }),
                    child: Container(
                      width: 44,
                      height: 35,
                      child: Center(
                        child: Image.asset(
                          'assets/images/icon_titile_qr.png',
                          width: 20,
                          height: 20,
                          color: Colors.black,
                        ),
                      ),
                    ),
                  )),
              10.horizontalSpace,
              // SizedBox(
              //   width: 15,
              // )
              // GestureDetector(
              //   onTap: () {
              //     RouteManager.push(context, RoutMapping.message());
              //   },
              //   child: _message(),
              // )
            ],
          ))
        ],
      ),
    );
  }
}
